package com.spiro.test.net.tcp.ssl.bidirectional;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Created by tz0643 on 2016/6/17.
 *
 * JVM options:
 *
 *   -Djavax.net.ssl.keyStore=C:\Users\tz0643\Desktop\jsse\sslclientkeys
 *   -Djavax.net.ssl.keyStorePassword=123456
 *   -Djavax.net.ssl.trustStore=C:\Users\tz0643\Desktop\jsse\sslclienttrust
 *   -Djavax.net.ssl.trustStorePassword=123456
 */
public class SSLTcpClientWithJVMOptions {

    private SSLSocket socket = null;
    private BufferedReader reader = null;
    private PrintWriter writer = null;

    public void start(int port) throws IOException {
        try {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) factory.createSocket("localhost", port);
            System.out.println("Connected, port -> " + port);
        } catch (IOException e) {
            throw e;
        }

        try {
            reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            writer = new PrintWriter(this.socket.getOutputStream());

            Scanner scanner = new Scanner(System.in);

            while (true) {
                System.out.println("input -> ");
                String input = scanner.next();
                writer.println(input);
                writer.flush();

                String returnLine = reader.readLine();
                System.out.println(returnLine);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
            if (writer != null) {
                writer.close();
            }

            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void main(String[] args) {
        SSLTcpClientWithJVMOptions tcpClient = new SSLTcpClientWithJVMOptions();
        try {
            tcpClient.start(9000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
